package com.yxt.qmgf.minesweeper.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yxt.qmgf.minesweeper.model.mineScore;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class FileScoreService {
    private static final String SCORE_FILE_PATH = "mine_scores.json";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 注册Java 8时间模块
        objectMapper.findAndRegisterModules();
    }

    /**
     * 添加积分记录
     */
    public static void addRecord(String user, int scores,String score) {
        try {
            List<mineScore> records = loadRecords();
            records.add(new mineScore(
                    user,
                    scores,
                    LocalDateTime.now(),
                    score
            ));
            saveRecords(records);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户的所有积分记录
     */
    public static List<mineScore> getRecordsByUser(String username) {
        try {
            List<mineScore> allRecords = loadRecords();
            List<mineScore> userRecords = new ArrayList<>();

            for (mineScore record : allRecords) {
                if (record.getUsername().equals(username)) {
                    userRecords.add(record);
                }
            }
            return userRecords;
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 加载所有记录
     */
    private static List<mineScore> loadRecords() throws IOException {
        File file = new File(SCORE_FILE_PATH);
        if (!file.exists()) {
            return new ArrayList<>();
        }

        byte[] jsonData = Files.readAllBytes(Paths.get(SCORE_FILE_PATH));
        return objectMapper.readValue(jsonData, new TypeReference<List<mineScore>>(){});
    }

    /**
     * 保存所有记录
     */
    private static void saveRecords(List<mineScore> records) throws IOException {
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(records);
        Files.write(Paths.get(SCORE_FILE_PATH), json.getBytes());
    }
}
